package Database;

import java.sql.*;

import Model.Credential;
import Model.Staff;

//import Database.DBConnection;

public class CredentialDB
{
	public static Credential getCredentials(String credID)
	{
		Connection con = DBConnection.connect(true);
		PreparedStatement stmt = null;
		ResultSet rs = null;
		String select = "SELECT * FROM credential WHERE Credential_ID = ?";
		Credential cred = null;

		try
		{
			stmt = con.prepareStatement(select);
			stmt.setString(1, credID);
			rs = stmt.executeQuery();
			while(rs.next())
			{
				cred = new Credential();
				cred.setId(credID);
				cred.setPassword(rs.getString("Credential_Password"));
				cred.setRole(rs.getString("Credential_Role"));
				cred.setDateUpdated(rs.getString("Credential_DateUpdated"));
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			cred = null;
		}
		finally
		{
			try
			{
				if (rs != null)
					rs.close();
				if (stmt != null)
					stmt.close();
				if (con != null)
					con.close();
			}
			catch (SQLException e)
			{
			}
		}

		return cred;
	}
	
	public static Staff getStaffName(String credID)
	{
		Connection con = DBConnection.connect(true);
		PreparedStatement stmt = null;
		ResultSet rs = null;
		String select = "SELECT Credential_ID, Staff_Name FROM staff INNER JOIN credential ON credential.Credential_ID = staff.Staff_LoginID WHERE credential_id = ?";
		Staff staff = null;
		System.out.println(select);
		try
		{
			stmt = con.prepareStatement(select);
			stmt.setString(1, credID);
			rs = stmt.executeQuery();
			while(rs.next())
			{
				staff = new Staff();
				staff.setId(credID);
				staff.setName(rs.getString("Staff_Name"));
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			staff = null;
		}
		finally
		{
			try
			{
				if (rs != null)
					rs.close();
				if (stmt != null)
					stmt.close();
				if (con != null)
					con.close();
			}
			catch (SQLException e)
			{
			}
		}

		return staff;
	}
	
	public static void updateRole(String id, String newRole)
	{
		Connection con = DBConnection.connect(true);
		PreparedStatement stmt = null;
		String select = "UPDATE Credential SET Credential_Role=? WHERE Credential_ID = ?";
		
		try
		{
			stmt = con.prepareStatement(select);
			stmt.setString(1, newRole);
			stmt.setString(2, id);
			
			stmt.executeUpdate();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (stmt != null)
					stmt.close();
				if (con != null)
					con.close();
			}
			catch (SQLException e)
			{
			}
		}
	}
}
